package com.hycat.mail.search.service.Impl;

import com.alibaba.fastjson.JSON;
import com.hycat.mail.common.constant.EsConstant;
import com.hycat.mail.common.to.es.SkuEsModel;
import com.hycat.mail.search.config.ElasticSearchConfig;
import com.hycat.mail.search.service.ProductSaveService;
import com.sun.org.apache.xpath.internal.operations.Bool;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.util.List;

/**
 * @author : lzhycat
 * @date : 2022-07-29 14:13
 */
public class ProductSaveServiceImpl implements ProductSaveService {
    @Autowired
    private RestHighLevelClient client;

    @Override
    public boolean productSpuUp(List<SkuEsModel> skuEsModels) throws IOException {
        BulkRequest bulkRequest = new BulkRequest();
        for(SkuEsModel skuEsModel : skuEsModels) {
            IndexRequest request = new IndexRequest(EsConstant.PRODUCT_INDEX).id(skuEsModel.getSkuId().toString());
            request.source(JSON.toJSONString(skuEsModel), XContentType.JSON);
            bulkRequest.add(request);
        }

        BulkResponse response = client.bulk(bulkRequest, ElasticSearchConfig.COMMON_OPTIONS);
        //成功则返回false
        return response.hasFailures();
    }
}
